import React from 'react'
import { inject, observer } from 'mobx-react';
import { toJS } from "mobx"
import { List, ActivityIndicator, DatePicker, Modal, Checkbox, Icon, Tools } from 'weaver-mobile'
import { Form, RouteLayout } from 'weaver-mobile-page';
import { withRouter, Route } from 'react-router-dom';
import SaveAsTemplate from './SaveAsTemplate';
import SelectIdentatity from './SelectIdentatity';


const ButtonGroup = RouteLayout.ButtonGroup;
const AgreeItem = Checkbox.AgreeItem;
// const CheckboxItem = Checkbox.CheckboxItem;
const FormItem = List.FormItem;
const { DatePickerInput } = DatePicker;
const getLabel = Tools.getLabel;
@inject('wfAgentStore')
@withRouter
@observer
export default class AddAgent extends React.Component {
    componentDidMount() {
        const { location } = this.props;
        const { pathname = "" } = location;
        const { addAgent, initAddAgentDom, getPageTitle, setAddAgent } = this.props.wfAgentStore;
        const { symbol = "", templateid = 0 } = addAgent;
        let params = {}
        if (templateid === 0) {
            params = { "symbol": symbol }
        } else {
            params = { "symbol": symbol, "templateid": templateid }
        }
        getPageTitle(pathname, symbol);
        setAddAgent({ symbol: symbol })
        initAddAgentDom(params);

    }

    componentWillUpdate() {
        const { location, wfAgentStore } = this.props;
        const { getPageTitle, addAgent } = wfAgentStore;
        const { symbol = "" } = addAgent;
        const { pathname = "" } = location;
        getPageTitle(pathname, symbol);
    }
    componentWillUnmount() {//卸载
        const { setAddAgent, setImportFromTemData } = this.props.wfAgentStore;
        setAddAgent({ isInAddAgent: false })
        setImportFromTemData({ isAdvancedSearching: false, selectedRowKeys: "" })
    }

    getTimeUtil(time) {
        let newTime = "";
        if (time) {
            newTime = time;
        }
        return newTime;
    }

    //点击保存
    onOk = (num) => {
        const { addAgent, saveAgentTemplate, verifyAgentOverlap, setAddAgent, changeItemtoNUM, agentTemplateList, formValidation, initDatas } = this.props.wfAgentStore;
        const { symbol = "", templateid, form, beginTime, beginDate, endDate, endTime, layout, bagentuid_identatity, default_bagentuid } = addAgent;
        let savePramas = toJS(form.formParams)
        let newbeginTime, newbeginDate, newendDate, newendTime;

        //把null转换成"";
        newbeginTime = this.getTimeUtil(beginTime);
        newbeginDate = this.getTimeUtil(beginDate);
        newendDate = this.getTimeUtil(endDate);
        newendTime = this.getTimeUtil(endTime);
        if (savePramas.hasOwnProperty("beginDate")) {
            savePramas.beginDate = newbeginDate
        }
        if (savePramas.hasOwnProperty("beginTime")) {
            savePramas.beginTime = newbeginTime
        }
        if (savePramas.hasOwnProperty("endDate")) {
            savePramas.endDate = newendDate
        }
        if (savePramas.hasOwnProperty("endTime")) {
            savePramas.endTime = newendTime
        }
        changeItemtoNUM(savePramas);
        if (savePramas.hasOwnProperty("userSelect")) {
            if (toJS(form.formParams.bagentuid) === toJS(default_bagentuid)) {
                savePramas.userSelect = bagentuid_identatity.key;
            } else {
                let newobj = {};
                for (let key in savePramas) {
                    if (key !== "userSelect") {
                        newobj[key] = savePramas[key];
                    }
                }
                savePramas = newobj;
            }
        }
        let flag = formValidation(savePramas);
        if (flag) {
            if (symbol === "addAgent") {//新建代理
                if (num) {
                    verifyAgentOverlap({
                        ...savePramas,
                        method: "add",
                    }, this.overLapCallback)
                    setAddAgent({ savePramas: savePramas });
                } else {
                    this.props.history.push(layout.path)
                }
            } else if (symbol === "importTemplate") {//从模板导入并新建代理
                verifyAgentOverlap({
                    ...savePramas,
                    method: "add",
                }, this.overLapCallbackimp)
                setAddAgent({ savePramas: savePramas });
            } else if (symbol === "addTemplate") {//新建模板
                saveAgentTemplate({
                    ...savePramas,
                }, () => {
                    const { setTempMDatas } = this.props.wfAgentStore;
                    setTempMDatas({ searchParams: {} })
                    agentTemplateList();
                    this.props.history.go(-1);
                })
            } else if (symbol === "editTemplate") {//编辑模板
                saveAgentTemplate({
                    ...savePramas,
                    templateid: templateid,
                }, () => {
                    const { searchTemplate } = this.props.wfAgentStore;
                    searchTemplate();
                    this.props.history.go(-1);
                })
            }
        }
    }


    overLapCallback = (callbakcdatas) => {
        const { setAddAgent, addAgent } = this.props.wfAgentStore;
        // const { radioChecked } = addAgent;
        const { overlapCount = 0 } = callbakcdatas;
        if (overlapCount > 0) {
            let title = <span>{getLabel(82666, "当前代理设置与已有")} <span style={{ fontWeight: "bold", color: "red" }}>{overlapCount}</span> {getLabel(383526, "条代理设置重复请选择重复数据处理方式")}</span>;
            setAddAgent({ title: title, isShowCheckModal: true })
        } else {
            this.onSaveAddAgent();
        }
    }
    overLapCallbackimp = (callbakcdatas) => {
        const { setAddAgent, addAgent } = this.props.wfAgentStore;
        const { radioChecked } = addAgent;
        const { overlapCount = 0, overlapIds } = callbakcdatas;
        if (overlapCount > 0) {
            let title = <span>{getLabel(82666, "当前代理设置与已有")} <span style={{ fontWeight: "bold", color: "red" }}>{overlapCount}</span> {getLabel(383526, "条代理设置重复请选择重复数据处理方式")}</span>;
            setAddAgent({ title: title, isShowCheckModal: true })
        } else {
            this.onSaveAddAgentimp();
        }
    }
    onCheckBoxChange = (val) => {
        const { setAddAgent } = this.props.wfAgentStore;
        setAddAgent({ radioChecked: val })
    }
    onChange = (condition, value) => {
        const { wfAgentStore } = this.props;
        const { addAgent } = wfAgentStore;
        const { form } = addAgent;
        form.onChange(condition, value);
    }

    getSearchs = () => {
        const { wfAgentStore } = this.props;
        const { addAgent, setResultDatasState } = wfAgentStore;
        const { datas = {}, form, symbol, beginDate, beginTime, endDate, endTime, default_bagentuid, bagentuid_identatity } = addAgent;
        const { fields = {} } = datas;
        let formParams = form.formParams;
        if (!form.isInit) { return; }
        let items = [];
        if (fields.hasOwnProperty('templatename')) {
            items.push(
                <Form.Item
                    key={fields.templatename.domkey.join('__')}
                    form={form}
                    fieldConfig={fields.templatename}
                    onChange={this.onChange}
                />
            )
        }
        if (fields.bagentuid) {
            items.push(
                <Form.Item
                    key={fields.bagentuid.domkey.join('__')}
                    form={form}
                    fieldConfig={fields.bagentuid}
                    onChange={this.onChange}
                />);
        }
        if (fields.userSelect && (toJS(form.formParams.bagentuid) === toJS(default_bagentuid))) {
            items.push(
                <div
                    className="wf-addagent-userSelect"
                    key={fields.userSelect.domkey.join('__')}
                    onClick={() => {
                        const { addAgent } = this.props.wfAgentStore;
                        const { layout_SelectIdentatity } = addAgent;
                        this.props.history.push(layout_SelectIdentatity.path);
                    }}
                >
                    <FormItem
                        label=""
                        extra={<Icon type="right" />}
                        line="true"
                        content={bagentuid_identatity.showname} />
                </div>
            );
        }

        if (fields.agentuid) {
            items.push(
                <Form.Item
                    key={fields.agentuid.domkey.join('__')}
                    form={form}
                    fieldConfig={fields.agentuid}
                    onChange={this.onChange}
                />);
        }
        if (symbol === 'addAgent' || symbol === 'importTemplate') {
            let date = new Date();
            let month = '' + (date.getMonth() + 1);
            let day = '' + date.getDate();
            let year = '' + date.getFullYear();
            let hour = '' + date.getHours();
            let min = '' + date.getMinutes();
            if (month.length < 2) month = '0' + month;
            if (day.length < 2) day = '0' + day;
            if (hour.length < 2) hour = '0' + hour;
            if (min.length < 2) min = '0' + min;
            let nowDate = year + "-" + (date.getMonth() + 1) + "-" + month + "-" + day;
            let nowTime = hour + ":" + min;
            if (fields.beginDate) {
                items.push(
                    <div className="form-time-wrap" key={"beginDate"}>
                        <FormItem
                            key={"beginDate"}
                            wrap="nowrap"
                            label={getLabel(740, "开始日期")}
                            extra={<Icon type="right" />}
                            content={(
                                <DatePickerInput
                                    placeholder={getLabel(763, "不限")}
                                    mode="date"
                                    key={"beginDate"}
                                    minDate={nowDate}
                                    maxDate={endDate || "2030-12-30"}
                                    value={beginDate}
                                    onChange={date => setResultDatasState({ "beginDate": date })}
                                />
                            )}
                        />
                    </div>
                )
            }
            if (fields.beginTime) {
                items.push(
                    <div className="form-time-wrap" key={"beginTime"}>
                        <FormItem
                            key={"beginTime"}
                            wrap="nowrap"
                            label={getLabel(500371, "开始时间")}
                            extra={<Icon type="right" />}
                            content={(
                                <DatePickerInput
                                    placeholder={getLabel(763, "不限")}
                                    mode="time"
                                    value={beginTime}
                                    key={"beginTime"}
                                    onChange={time => {
                                        setResultDatasState({ "beginTime": time });
                                    }}
                                />
                            )}
                        />
                    </div>
                )
            }
            if (fields.endDate) {
                items.push(
                    <div className="form-time-wrap" key={"endDate"}>
                        <FormItem
                            key={"endDate"}
                            wrap="nowrap"
                            label={getLabel(741, "结束日期")}
                            extra={<Icon type="right" />}
                            content={(
                                <DatePickerInput
                                    placeholder={getLabel(763, "不限")}
                                    mode="date"
                                    key={"endDate"}
                                    minDate={beginDate || nowDate}
                                    maxDate="2030-12-30"
                                    value={endDate}
                                    onChange={date => {
                                        setResultDatasState({ "endDate": date });
                                    }}
                                />
                            )}
                        />
                    </div>
                )
            }
            if (fields.endTime) {
                items.push(
                    <div className="form-time-wrap" key={"endTime"}>
                        <FormItem
                            key={"endTime"}
                            wrap="nowrap"
                            label={getLabel(500372, "结束时间")}
                            extra={<Icon type="right" />}
                            content={(
                                <DatePickerInput
                                    placeholder={getLabel(763, "不限")}
                                    mode="time"
                                    key={"endTime"}
                                    value={endTime}
                                    onChange={time => {
                                        setResultDatasState({ "endTime": time });
                                    }}
                                />
                            )}
                        />
                    </div>
                )
            }
        }
        if (fields.isCreateAgenter) {
            items.push(
                <Form.Item
                    key={fields.isCreateAgenter.domkey.join('__')}
                    form={form}
                    fieldConfig={fields.isCreateAgenter}
                    onChange={this.onChange}
                />);
        }
        if (fields.isSysCreateAgenter && formParams.isCreateAgenter) {
            items.push(
                <Form.Item
                    key={fields.isSysCreateAgenter.domkey.join('__')}
                    form={form}
                    fieldConfig={fields.isSysCreateAgenter}
                    onChange={this.onChange}
                />);
        }
        if (fields.isProxyDeal) {
            items.push(
                <Form.Item
                    key={fields.isProxyDeal.domkey.join('__')}
                    form={form}
                    fieldConfig={fields.isProxyDeal}
                    onChange={this.onChange}
                />);
        }
        if (fields.isPendThing && formParams.isProxyDeal) {
            items.push(
                <Form.Item
                    key={fields.isPendThing.domkey.join('__')}
                    form={form}
                    fieldConfig={fields.isPendThing}
                    onChange={this.onChange}
                />);
        }
        if (fields.agentrange) {//代理流程范围
            items.push(
                <div className="wf-agent-agentrange-item" key={fields.agentrange.domkey.join('__')}>
                    <Form.Item
                        key={fields.agentrange.domkey.join('__')}
                        form={form}
                        fieldConfig={fields.agentrange}
                        onChange={this.onChange}
                    />
                </div>
            );
        }

        if (form.formParams.agentrange === "1") {
            if (fields.rangetype) {
                items.push(
                    <Form.Item
                        key={fields.rangetype.domkey.join('__')}
                        form={form}
                        fieldConfig={fields.rangetype}
                        onChange={this.onChange}
                    />);
            }
        }

        const group = (
            <Form style={{ height: '100%' }} >
                <List>
                    {items}
                </List>
            </Form>
        )
        return group;
    }

    /**主表单组件 */
    addAgentComponent = () => {
        const { addAgent } = this.props.wfAgentStore;
        const { symbol = "", layout } = addAgent;
        const btns = [{
            key: 'saveAsTemplate',
            text: getLabel(18418, "存为模板"),
            onClick: () => {
                this.onOk(0)
            },
            type: '',
        }, {
            key: 'save',
            text: getLabel(86, "保存"),
            onClick: () => { this.onOk(1) },
            type: 'primary',
        }]
        return (
            <div className='wf-agent-addagent-addAgentComponent'>
                <div className="addAgent-form" >
                    {this.getSearchs()}
                </div>
                <div className='wf-agent-addagent-button-group'>
                    <ButtonGroup data={symbol === "addAgent" ? btns : btns.slice(1, 2)} />
                </div>
            </div>
        )
    }

    onSaveAddAgent = (type) => {
        const { addAgentSave, initDatas, getAgentDatas, addAgent, setAddAgent } = this.props.wfAgentStore;
        const { savePramas, radioChecked } = addAgent;
        const { listParams } = initDatas;
        addAgentSave({
            ...savePramas,
            method: "add",
            overlapMethod: radioChecked,
        }, () => {
            setAddAgent({ title: "", isShowCheckModal: false, radioChecked: 1 })
            this.props.history.go(-1);
            getAgentDatas(listParams);
        })
    }

    onSaveAddAgentimp = () => {
        const { addAgentSave, initDatas, getAgentDatas, addAgent, setAddAgent } = this.props.wfAgentStore;
        const { savePramas, radioChecked } = addAgent;
        const { listParams } = initDatas;
        addAgentSave({
            ...savePramas,
            method: "add",
            overlapMethod: radioChecked,
        }, () => {
            setAddAgent({ title: "", isShowCheckModal: false, radioChecked: 1 })
            this.props.history.push("/agent/mineAgentSet");
        })
    }

    render() {
        const { location } = this.props;
        const { pathname = "" } = location;
        const { addAgentSave, setAddAgent, addAgent, getPageTitleSub } = this.props.wfAgentStore;
        const { isShowLoading, layout, isShowCheckModal, title, radioChecked, symbol, list_selectIdentatity,layout_SelectIdentatity } = addAgent;
        let buttonGroupData_selectIdentatity = [
            {
                key: 'submit',
                text: getLabel(826,'确定'),
                onClick: () => list_selectIdentatity.selectedRowKeys.length > 0 &&this.props.history.go(-1),
                className: list_selectIdentatity.selectedRowKeys.length > 0 ? "abled" : "disabled"
            }]
        return (
            <div className="wf-agent-addAgent-part">
                {/* <div className="wf_agent_page_title">{getPageTitleSub(pathname, symbol)}</div> */}
                {this.addAgentComponent()}
                {isShowCheckModal &&
                    <Modal
                        visible={isShowCheckModal}
                        transparent
                        title={title}
                        footer={isShowCheckModal && [
                            {
                                text: getLabel(201, '取消'), onPress: () => {
                                    setAddAgent({ title: "", isShowCheckModal: false, radioChecked: 1 })
                                }
                            },
                            {
                                text: getLabel(826, '确定'), onPress: () => {
                                    setAddAgent({ isShowCheckModal: false })
                                    if (symbol === "addAgent") {
                                        this.onSaveAddAgent();
                                    } else if (symbol === "importTemplate") {
                                        this.onSaveAddAgentimp();
                                    }
                                }
                            }
                        ]}
                    >
                        {isShowCheckModal && <div>
                            <AgreeItem
                                style={{ marginLeft: "0" }}
                                key={1}
                                defaultChecked
                                checked={radioChecked === 1 ? true : false}
                                onChange={() => this.onCheckBoxChange(1)}
                            ><span style={{ fontSize: "13px" }}>{getLabel(82669, "从新保存的代理设置中去除重复设置内容")}</span>
                            </AgreeItem>
                            <AgreeItem
                                style={{ marginLeft: "0" }}
                                key={2}
                                checked={radioChecked === 2 ? true : false}
                                onChange={() => this.onCheckBoxChange(2)}
                            ><span style={{ fontSize: "13px" }}>{getLabel(82670, "以新保存的代理设置替换已有重复的代理设置")}</span>
                            </AgreeItem>
                            {/**下面的代码也是可以达到相同的效果 */}
                            {/* <Radio checked={radioChecked === 1 ? true : false} onChange={() => this.onCheckBoxChange(1)}>Agree</Radio>
                        <Radio checked={radioChecked === 2 ? true : false} onChange={() => this.onCheckBoxChange(2)}>Agree</Radio> */}
                        </div>}
                    </Modal>
                }
                <Route
                    key={layout.id}
                    path={layout.path}
                    render={() => (
                        <RouteLayout>
                            <div
                                key="wmPoutePageDemo"
                                className="wm-route-layout"
                            >
                                <SaveAsTemplate />
                            </div>
                        </RouteLayout>
                    )}
                />
                <Route
                    key={layout_SelectIdentatity.id}
                    path={layout_SelectIdentatity.path}
                    render={() => (
                        <RouteLayout>
                            <div
                                key="wf-addgent-SelectIdentatity"
                                className="wm-route-layout"
                            >
                                <SelectIdentatity />
                                <ButtonGroup data={buttonGroupData_selectIdentatity} />
                            </div>

                        </RouteLayout>
                    )}
                />
                {isShowLoading && <ActivityIndicator
                    toast
                    text={getLabel(500408 , "加载中...")}
                    animating={isShowLoading}
                />}
            </div>)
    }

}

